<script setup>
import { ref, reactive, onMounted, nextTick, watchEffect } from 'vue'
import router from "@/router/index.js";
import { useRoute } from 'vue-router';
const route = useRoute();

const items = [
  { name: '首页', route: 'home' },
  { name: '通知公告', route: 'notices' },
  { name: '招聘岗位', route: 'jobs' },
  { name: '政策文件', route: 'policy' }
]
const activeIndex = ref(0)
const itemRefs = reactive([])
const indicatorStyle = reactive({
  width: '0px',
  left: '0px'
})

// 自动匹配当前路由
watchEffect(async () => {
  const currentRoute = route.path.split('/').pop()
  const index = items.findIndex(item => item.route === currentRoute)
  if (index !== -1){
    activeIndex.value = index
    await nextTick()
    updateIndicator()
  }
})

// 设置元素引用
const setItemRef = (el, index) => {
  if (el) itemRefs[index] = el
}

// 切换导航项
const switchItem = async (index) => {
  await router.push(`/index/${items[index].route}`)
}

// 更新指示条位置
const updateIndicator = () => {
  const activeItem = itemRefs[activeIndex.value]
  if (activeItem) {
    indicatorStyle.width = `${activeItem.offsetWidth}px`
    indicatorStyle.left = `${activeItem.offsetLeft}px`
  }
}

// 初始化及窗口变化时更新
onMounted(async () => {
  await nextTick()
  updateIndicator()
  window.addEventListener('resize', updateIndicator)
})
</script>

<template>
  <div class="container">
    <!-- 导航条 -->
    <nav class="nav-bar">
      <div v-for="(item, index) in items" :key="index" class="nav-item" @click="switchItem(index)" :ref="el => setItemRef(el, index)">
        {{ item.name }}
      </div>
      <div class="indicator" :style="indicatorStyle"></div>
    </nav>
  </div>
    <!-- 添加路由出口 -->
    <router-view></router-view>
</template>

<style scoped>
.container {
  width: 100%;
  background: #F0F8FF;
}

.nav-bar {
  position: relative;
  display: flex;
  justify-content: flex-start; /* 左对齐 */
  align-items: center;
  width: 30%; /* 40% - 10% = 30% 宽度 */
  margin-left: 10%; /* 距离左边10% */
  height: 50px;
  padding: 0 20px;
  gap: 12%; /* 控制词语间距 */
}

.nav-item {
  flex: 0 0 auto; /* 非均匀分布 */
  padding: 0 8px; /* 词语内边距 */
  cursor: pointer;
  transition: color 0.3s;
  position: relative;
  white-space: nowrap; /* 防止文字换行 */
}

.indicator {
  position: absolute;
  bottom: 0;
  height: 3px;
  background: #00008B;
  transition: all 0.3s ease;
}

.nav-item:hover {
  color: #409eff;
}
</style>